package com.googlecode.garbagecan.clickstudy.page.customer;

import com.googlecode.garbagecan.clickstudy.BorderTemplate;
import com.googlecode.garbagecan.clickstudy.service.customer.CustomerService;
import org.apache.click.control.*;
import org.apache.click.extras.control.LinkDecorator;
import org.apache.click.util.Bindable;

public class Customers extends BorderTemplate {
	@Bindable
	protected String title = "Customers";

	@Bindable
	protected Table table = new Table();

	@Bindable
	protected PageLink addLink = new PageLink("Add", AddCustomer.class);
	
	@Bindable
	protected PageLink editLink = new PageLink("Edit", EditCustomer.class);

	@Bindable
	protected ActionLink deleteLink = new ActionLink("Delete", this, "onDeleteClick");

	public Customers() {
		setStateful(true);

		addLink.setTitle("Add customer");

		table.setClass(Table.CLASS_ITS);
		table.setPageSize(10);
		table.setShowBanner(true);
		table.setSortable(true);

		table.addColumn(new Column("id"));
		table.addColumn(new Column("name"));
		Column column = new Column("email");
		column.setAutolink(true);
		column.setTitleProperty("name");
		table.addColumn(column);
		table.addColumn(new Column("investments"));

		editLink.setTitle("Edit customer details");

		deleteLink.setTitle("Delete customer record");
		deleteLink.setValue("Delete");
		deleteLink.setAttribute("onclick", "return window.confirm('Are you sure you want to delete this record?');");

		column = new Column("Action");
		column.setTextAlign("center");
		AbstractLink[] links = new AbstractLink[]{editLink, deleteLink};
		column.setDecorator(new LinkDecorator(table, links, "id"));
		column.setSortable(false);
		table.addColumn(column);
	}
	
	public boolean onDeleteClick() {
		Integer id = deleteLink.getValueInteger();
		CustomerService.getInstance().delete(id.intValue());
		return true;
	}

	@Override
	public void onRender() {
		table.setRowList(CustomerService.getInstance().getAllCustomers());
	}
}
